package com.foreknow.dao.impl;

import com.foreknow.dao.GuestbookDao;

import com.foreknow.db.DBManager;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Guestbook;
import com.foreknow.model.student;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class GuestbookDaoImpl extends BaseDAO implements GuestbookDao {

    @Override
    public boolean save(Guestbook gb) throws SQLException {
        String sql = "insert into guestbook(sname,phone,email,title,content,createdTime) values(?,?,?,?,?,?)";
        int i = jdbcTemplate.update(sql,gb.getName(),gb.getPhone(),gb.getEmail(),gb.getTitle(),gb.getContent(),gb.getCreatedTime());
        return i==1;
    }

    @Override
    public List<Object> getQueryAll() throws SQLException {
        String sql = "select * from guestbook";
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jdbcTemplate.query(sql,mapping);
        return list;
    }



    @Override
    public Guestbook getQueryById(int id) throws SQLException {
        String sql = "select * from guestbook where id=?";
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jdbcTemplate.query(sql,mapping,id);
        if(list.size()>0) {
            Guestbook gb = (Guestbook) list.get(0);
            return gb;
        }
        return null;
    }

    @Override
    public boolean deleteById(Integer id) throws SQLException {
        String sql = "delete from guestbook where id=?";
        int isRigth = jdbcTemplate.update(sql,id);
        return isRigth==1;
    }

    @Override
    public boolean update(Guestbook gb) throws SQLException {
        String sql="update guestbook set sname=?,phone=?,email=?,title=?,content=?,createdTime=? where id=?";
        int isRight=jdbcTemplate.update(sql,gb.getName(),gb.getPhone(),gb.getEmail(),gb.getTitle(),gb.getContent(),gb.getCreatedTime(),gb.getId());
        return isRight==1;
    }

    public static void main(String[] args) {
        GuestbookDaoImpl dao = new GuestbookDaoImpl();
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //调用的是BaseDAO中的setConnection(conn)方法
        dao.setConnection(conn);
        Guestbook gb = null;
        try {
            gb = dao.getQueryById(18);
            gb.setName("wei");
            gb.setPhone("110");
            gb.setEmail("666");
            gb.setTitle("non");
            gb.setContent("555");
            gb.setCreatedTime("test");
            boolean update = dao.update(gb);
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



}
